package com.cccccc.config;

import com.alibaba.fastjson2.JSON;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * --- 代码敲对！ ---
 *
 * @author CCCccc
 * @create 2025/8/22
 * 备注：
 * AuthenticationEntryPointImpl类是Spring Security的AuthenticationEntryPoint实现类，用于处理未认证的请求。
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        HashMap<String, String> result = new HashMap<>(); // 创建一个HashMap对象
        result.put("code", "403"); // 设置code为403
        result.put("msg", "未登录，请先登录");
        response.setContentType("application/json;charset=utf-8"); // 设置响应内容类型为JSON格式
        response.getWriter().write(JSON.toJSONString(result)); // 将HashMap对象转换为JSON字符串并写入响应
    }
}
